package com.station.util;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.util.Util;
import com.station.listener.LoadImageListener;

import java.io.File;
import java.io.FileOutputStream;

/**
 * Created by nbzl on 2017/10/24.
 */
public class GlideHelper {
    private Context context;
    public static GlideHelper glideHelper;

    public static GlideHelper getInstance(Context context){
        if(glideHelper==null){
            glideHelper=new GlideHelper();
        }
        glideHelper.context=context;
        return glideHelper;
    }

    public void downLoadImg(final String filename, String url,final Object object, final LoadImageListener listener){
        if (Util.isOnMainThread()) {{
            Glide.with(context).load(url).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
                @Override
                public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
                    try {
                        savaFileToSD(filename,bytes,object,listener);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                       Log.e("Mytext","onLoadFailed");
                       listener.failload();
                }
            });
        }}

    }

    public void savaFileToSD(String filename, byte[] bytes,Object object,LoadImageListener listener) throws Exception {
        //如果手机已插入sd卡,且app具有读写sd卡的权限
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String filePath = Environment.getExternalStorageDirectory().toString()+File.separator+Static.zl+File.separator+Static.basestation;
            File dir1 = new File(filePath);
            if (!dir1.exists()){
                dir1.mkdirs();
            }
            filename = filePath+ "/" + filename;
            //这里就不要用openFileOutput了,那个是往手机内存中写数据的
            FileOutputStream output = new FileOutputStream(filename);
            output.write(bytes);
            //将bytes写入到输出流中
            output.close();
            //关闭输出流
            Log.e("Mytext","图片已成功保存到"+filePath);
            listener.downloadImg(filename,object);
            //Toast.makeText(context, "图片已成功保存到"+filePath, Toast.LENGTH_SHORT).show();
        } else {
            //Log.e("Mytext","图片已成功保存到"+filePath);
            Toast.makeText(context, "SD卡不存在或者不可读写", Toast.LENGTH_SHORT).show();
        }
    }
}
